package com.tanhua.app.interceptor;

import com.tanhua.app.service.UserService;
import com.tanhua.db.User;
import com.tanhua.vo.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override  /*在控制器方法之前执行*/
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取app传递过来的token
        String token = request.getHeader("Authorization");
        if(token==null){
            response.setStatus(401);
            response.getWriter().print("权限不足...");
            return false;
        }
        // 根据token获取用户
        User user = userService.findUserByToken(token);
        if(user==null){
            response.setStatus(401);
            response.getWriter().print("权限不足...");
            return false;
        }
        // 将用户放入ThreadLocal中 在controller方法中取出（同一个）
        UserHolder.saveUser(user);
        // 放行
        return true;
    }

    @Override //整个程序结束
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //快速释放资源
        UserHolder.removeUser();
    }
}
